// 表格组件实现
/**
 * 
 * @param {*} x 左边
 * @param {*} y 顶边
 * @param {*} w 宽度
 * @param {*} h 高度
 * @param {*} headers 表头数组
 * @param {*} pageSize 分页大小
 * @param {*} buttons 表格右侧按钮数组,每个按钮包含title,css,callback，留空不显示
 * @param {*} autoWidth 自动调整列宽
 * @param {*} hide 是否隐藏
 * @param {*} tag 字符串标志
 * @param {*} callback 自定义回调函数
 * @param {*} divid 父divid,留空则添加到body
 * @returns 表格ID
 */
window.add_table = function(x, y, w, h, headers, pageSize, buttons, autoWidth, hide, tag, callback, divid) {
    // 参数默认值
    x = x || 100;
    y = y || 100;
    w = w || 600;
    h = h || 400;
    headers = headers || [];
    pageSize = pageSize || 0;
    buttons = buttons || [];
    autoWidth = autoWidth || false;
    hide = hide || false;
    tag = tag || '';
    console.log("tag:"+tag)
    callback = callback || null;

    // 生成唯一ID
    const id = 'table_' + Date.now() + '_' + Math.floor(Math.random() * 10000);

    // 创建表格容器
    const container = document.createElement('div');
    container.id = id;
    container.className = 'layui-table-container';

    // 设置样式
    container.style.position = 'absolute';
    container.style.left = x + 'px';
    container.style.top = y + 'px';
    container.style.width = w + 'px';
    container.style.height = h + 'px';
    if (hide) container.style.display = 'none';

    // 创建表格
    const table = document.createElement('table');
    table.className = 'layui-table';
    //table.setAttribute('id', 'table-'+id);
    
    // 创建表头
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    
    headers.forEach(header => {
        const th = document.createElement('th');
        th.textContent = header.name;
        if (!autoWidth && header.width) {
            th.style.width = header.width + 'px';
        }
        if (header.sortable) {
            th.setAttribute('lay-sort', '');
        }
        headerRow.appendChild(th);
    });
    
    // 如果有按钮组，添加操作列表头
    if (buttons.length > 0) {
        const actionTh = document.createElement('th');
        actionTh.textContent = '操作';
            // 动态计算操作列宽度
            const minWidth = 30; // 每个按钮最小宽度
            const padding = 2; // 按钮间间距调整为2px
            const totalWidth = buttons.reduce((sum, btn) => {
                // 估算按钮宽度：文本长度*8 + 内边距
                const btnWidth = Math.max(minWidth, (btn.title.length * 8) + 2);
                return sum + btnWidth + padding;
            }, 0);
            
            actionTh.style.width = Math.max(200, totalWidth) + 'px';
        headerRow.appendChild(actionTh);
    };
    
    thead.appendChild(headerRow);
    table.appendChild(thead);
    
    // 创建表体
    const tbody = document.createElement('tbody');
    table.appendChild(tbody);
    
    container.appendChild(table);
    
    // 存储按钮组信息
    if (buttons.length > 0) {
        // 确保elementStore.tables[id]已初始化
        if (!elementStore.tables[id]) {
            elementStore.tables[id] = {};
        }
        // 存储按钮组信息
        elementStore.tables[id].buttons = buttons;
    }
    
    // 添加到页面或指定父div
    const parent = divid ? document.getElementById(divid) : document.body;
    parent.appendChild(container);
    
    // 初始化表格存储空间
    if (!elementStore.tables) {
        elementStore.tables = {};
    }
    
    // 存储引用
    elementStore.tables[id] = {
        container: container,
        table: table,
        thead: thead,
        tbody: tbody,
        headers: headers,
        pageSize: pageSize,
        buttons: buttons,
        autoWidth: autoWidth,
        tag: tag,
        callback: callback,
        data: []
    };
    
    // 应用LayUI表格样式
    layui.use('table', function() {
        const table = layui.table;
        
        // 初始化表格
        table.init(id, {
            elem: '#' + id + ' table',
            id: 'table-'+id,
            page: pageSize > 0,
            limit: pageSize > 0 ? pageSize : 99999,
            autoSort: false,
            skin: 'line',
            even: true,
            done: function(res, curr, count) {
                // 分页回调
                console.log('当前实例 ID:', this.id); // 输出当前表格实例 ID  
            }
        });
        
    });
    
    return id;
}

// 添加表格行
window.add_table_row = function(id, rowCount) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return -1;
    
    rowCount = rowCount || 1;
    
    // 创建新行
    const tr = document.createElement('tr');
    
    // 添加单元格
    tableObj.headers.forEach((header, index) => {
        const td = document.createElement('td');
        

        
        tr.appendChild(td);
    });
    
    tableObj.tbody.appendChild(tr);
    return tr.rowIndex;
}

// 设置表格序号
window.set_table_id = function(id, colIndex, startNum) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    // 参数默认值处理
    colIndex = colIndex === undefined || colIndex === false ? 0 : colIndex;
    startNum = startNum === undefined || startNum === false ? 1 : startNum;
    
    // 获取表格数据
    const rows = tableObj.tbody.querySelectorAll('tr');
    
    // 遍历行并设置序号
    rows.forEach((row, index) => {
        const cells = row.querySelectorAll('td');
        if (cells.length > colIndex && colIndex >= 0) {
            cells[colIndex].textContent = startNum + index;
        }
    });
};

// 修改表头
window.upd_table_header = function(id, x, y, w, h, headers, pageSize, buttons, autoWidth, hide, tag) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    // 更新位置和尺寸
    if (x !== undefined) tableObj.container.style.left = x + 'px';
    if (y !== undefined) tableObj.container.style.top = y + 'px';
    if (w !== undefined) tableObj.container.style.width = w + 'px';
    if (h !== undefined) tableObj.container.style.height = h + 'px';
    if (hide !== undefined) tableObj.container.style.display = hide ? 'none' : 'block';
    if (tag !== undefined) tableObj.tag = tag;
    
    // 更新表头
    if (headers !== undefined) {
        tableObj.headers = headers;
        tableObj.thead.innerHTML = '';
        
        const headerRow = document.createElement('tr');
        
        headers.forEach(header => {
            const th = document.createElement('th');
            th.textContent = header.name;
            if (!autoWidth && header.width) {
                th.style.width = header.width + 'px';
            }
            if (header.sortable) {
                th.setAttribute('lay-sort', '');
            }
            headerRow.appendChild(th);
        });
        
        tableObj.thead.appendChild(headerRow);
    }
    
    // 更新分页设置
    if (pageSize !== undefined) {
        tableObj.pageSize = pageSize;
        layui.table.reload(id, {
            elem: '#' + id +'table',
            id: 'table-'+id,
            page: pageSize > 0,
            limit: pageSize > 0 ? pageSize : 99999
        });
    }
    
    // 更新按钮
    if (buttons !== undefined) {
        tableObj.buttons = buttons;
        
        // 移除旧按钮
        const oldToolbar = tableObj.container.querySelector('.layui-table-tool');
        if (oldToolbar) {
            tableObj.container.removeChild(oldToolbar);
        }
        
        // 添加新按钮
        if (buttons.length > 0) {
            const btnContainer = document.createElement('div');
            btnContainer.className = 'layui-table-tool';
            
            buttons.forEach(btn => {
                const button = document.createElement('button');
                button.className = 'layui-btn';
                button.textContent = btn.title;
                if (btn.css) {
                    button.style.cssText += btn.css;
                }
                button.onclick = function() {
                    if (btn.callback) {
                        btn.callback();
                    }
                };
                btnContainer.appendChild(button);
            });
            
            tableObj.container.insertBefore(btnContainer, tableObj.table);
        }
    }
    
    // 更新列宽设置
    if (autoWidth !== undefined) {
        tableObj.autoWidth = autoWidth;
        
        // 重新设置列宽
        const ths = tableObj.thead.querySelectorAll('th');
        ths.forEach((th, index) => {
            if (autoWidth) {
                th.style.width = '';
            } else if (tableObj.headers[index] && tableObj.headers[index].width) {
                th.style.width = tableObj.headers[index].width + 'px';
            }
        });
    }
}

// 添加表项
window.add_table_row = function(id, rowIndex, dataArray) {
    const tableObj = elementStore.tables[id];
    
    // 如果行索引为-1或大于当前行数，添加到末尾
    if (rowIndex === -1 || rowIndex >= tableObj.data.length) {
        rowIndex = tableObj.data.length;
    }
    
    // 创建新行
    const newRow = {
        cells: new Array(tableObj.headers.length).fill(''),
        remark: ''
    };
    
    // 如果有数据数组且长度匹配表头列数，填充数据
    if (Array.isArray(dataArray) && dataArray.length === tableObj.headers.length) {
        newRow.cells = [...dataArray];
    }
    
    // 插入新行
    tableObj.data.splice(rowIndex, 0, newRow);
    
    // 重新渲染表格
    renderTableData(tableObj);
    return rowIndex;
}

// 获取表格总行数
window.get_table_c = function(id) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return 0;
    return tableObj.data.length;
}

// 修改表项
window.upd_table_cell = function(id, rowIndex, colIndex, content) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    if (rowIndex >= 0 && rowIndex < tableObj.data.length && 
        colIndex >= 0 && colIndex < tableObj.headers.length) {
        tableObj.data[rowIndex].cells[colIndex] = content;
        renderTableData(tableObj);
    }
}

// 设置列内容
window.set_table_cell = function(id, rowIndex, colIndex, content, isall) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    // 如果行索引为-1，设置为最后一行
    if (rowIndex === -1) {
        rowIndex = tableObj.data.length - 1;
    }
    
    if (rowIndex >= 0 && rowIndex < tableObj.data.length && 
        colIndex >= 0 && colIndex < tableObj.headers.length) {
        
        // 处理数组内容填充
        if (isall && Array.isArray(content)) {
            for (let i = 0; i < content.length && colIndex + i < tableObj.headers.length; i++) {
                tableObj.data[rowIndex].cells[colIndex + i] = content[i];
            }
        } else {
            // 保持原有逻辑
            tableObj.data[rowIndex].cells[colIndex] = content;
        }
        
        renderTableData(tableObj);
    }
}

// 删除行
window.del_table_row = function(id, rowIndex) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    if (rowIndex >= 0 && rowIndex < tableObj.data.length) {
        tableObj.data.splice(rowIndex, 1);
        renderTableData(tableObj);
    }
}

// 清空表项
window.clear_table = function(id) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    tableObj.data = [];
    renderTableData(tableObj);
    
    // 重置分页
    if (tableObj.pageSize > 0) {
        layui.table.reload(id, {
            elem: '#' + id +'table',
            id: 'table-'+id,
            page: { curr: 1 }
        });
    }
}

// 渲染表格数据
function renderTableData(tableObj) {
    tableObj.tbody.innerHTML = '';
    tableObj.data.forEach((rowData, rowIndex) => {
        const tr = document.createElement('tr');
        
        rowData.cells.forEach((cell, colIndex) => {
            const td = document.createElement('td');
            td.textContent = cell;
            // 保留原始行列索引值

            

            // 添加单元格事件监听
            td.onclick = function() {
                handleEvent('table', tableObj.container.id, 1, cell, tableObj.tag, 0, 0, null, rowIndex, colIndex, tableObj.callback, tableObj.container.id);
            };
            
            td.onkeydown = function(e) {
                handleEvent('table', tableObj.container.id, 3, cell, tableObj.tag, 0, 0, e.key, rowIndex, colIndex, tableObj.callback, tableObj.container.id);
            };
            
            td.addEventListener('dblclick', function() {
                handleEvent('table', tableObj.container.id, 2, cell, tableObj.tag, 0, 0, null, rowIndex, colIndex, tableObj.callback, tableObj.container.id);
            });
            
            tr.appendChild(td);
        });
        
        // 添加操作列
        if (tableObj.buttons && tableObj.buttons.length > 0) {
            const actionTd = document.createElement('td');
            actionTd.className = 'layui-table-cell-action';
            
            tableObj.buttons.forEach(btn => {
                const btnLink = document.createElement('a');
                btnLink.className = 'eht-table-btn';
                if (btn.css) {
                    btnLink.className += ' ' + btn.css;
                }
                btnLink.style.cssText = 'min-width:30px;height:24px;line-height:24px;padding:0 2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px;border-radius:2px;display:inline-block;border:1px solid #d2d2d2;background-color:' + btn.rgb + ';color:#333;cursor:pointer;text-decoration:none;margin:0 2px;';
                btnLink.setAttribute('lay-event', btn.title);
                btnLink.textContent = btn.title;
                btnLink.onclick = function(e) {
                    e.preventDefault();
                    const btnIndex = tableObj.buttons.findIndex(b => b.title === btn.title);
                    if (typeof btn.callback === 'function') {
                        handleEvent('tablebutton', tableObj.container.id, 1, btn.title, '', 0, 0,-1, rowIndex,btnIndex,btn.callback,tableObj.container.id);
                    }
                };
                actionTd.appendChild(btnLink);
            });
            
            tr.appendChild(actionTd);
        }
        
        tableObj.tbody.appendChild(tr);
    });
    
    // 重新渲染表格

        console.log('实例 ID:', layui.table.cache); // 输出实例 ID  

    //layui.table.reload('table-'+tableObj.container.id);
}

// 删除表格
window.del_table = function(id) {
    const tableObj = elementStore.tables[id];
    if (!tableObj) return;
    
    // 从DOM中移除表格
    if (tableObj.container && tableObj.container.parentNode) {
        tableObj.container.parentNode.removeChild(tableObj.container);
    }
    
    // 从存储中删除
    delete elementStore.tables[id];
};

// 初始化表格存储空间
if (!elementStore.tables) {
    elementStore.tables = {};
}